import React, { useState, useEffect, useRef } from 'react';
import 'antd/dist/antd.css';
import { getNewsList } from './api';
import style from './news.module.css';
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Table, Button, Modal, Input } from 'antd';
import axios from 'axios';
import NewsForm from '@/components/News/NewsForm';
import moment from 'moment';
const { confirm } = Modal;
const { Search } = Input;
interface IData {
  id: number;
  title: string;
  imgUrl?: string;
  content: string;
  create_time: string;
}
const { box } = style;
export default function News() {
  const [dataSource, setdataSource] = useState<IData[]>([]);
  //搜索后的数据
  const [searchList, setSearchList] = useState([]);
  //添加按钮 弹窗
  const [isAddVisible, setisAddVisible] = useState(false);
  //
  const addForm = useRef(null);

  //
  const updateForm = useRef(null);
  //修改新闻 弹窗
  const [isUpdateVisible, setisUpdateVisible] = useState(false);
  //修改后的状态
  const [current, setcurrent] = useState(null);
  const getNew = async () => {
    await getNewsList().then((res) => {
      // console.log(res.data)
      setdataSource(res.data);
    });
  };
  useEffect(() => {
    getNew();
  }, []);
  //删除弹窗
  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        //   console.log('OK');
        deleteMethod(item);
      },
      onCancel() {
        //   console.log('Cancel');
      },
    });
  };
  //删除
  const deleteMethod = (item) => {
    setdataSource(dataSource.filter((data) => data.id !== item.id));
    //需要链接后台
    axios.delete(`http://localhost:3004/news/${item.id}`);
  };
  //添加
  const addFormOK = () => {
    //addForm中有很多方法 其中一种 下面console了
    addForm.current
      .validateFields()
      .then((value) => {
        // console.log(value)

        setisAddVisible(false);

        //post到后端，生成id，再设置 datasource, 方便后面的删除和更新
        axios
          .post(`http://localhost:3004/news`, {
            ...value,
          })
          .then((res) => {
            console.log(res.data);
            setdataSource([...dataSource, res.data]);
          });
      })
      .catch((err) => {
        console.log(err);
      });
  };
  //修改
  const handleUpdate = (item) => {
    //并不保证是同步的
    setTimeout(() => {
      setisUpdateVisible(true);
      updateForm.current.setFieldsValue(item);
    }, 50);
    setcurrent(item);
  };
  //添加
  const addNews = () => {
    setisAddVisible(true);
    //重新点开弹窗   清空内容
    addForm.current.resetFields();
  };
  const updateFormOK = () => {
    updateForm.current.validateFields().then((value) => {
      // console.log(value)
      setisUpdateVisible(false);
      setdataSource(
        dataSource.map((item) => {
          if (item.id === current.id) {
            return {
              ...item,
              ...value,
            };
          }
          return item;
        })
      );
      axios.patch(`http://localhost:3004/news/${current.id}`, value);
    });
  };
  //搜索
  const onSearch = (value) => {
    // console.log(111)
    const result = dataSource.filter((item) => item.title.includes(value));
    if (value === '') {
      // message.warning('输入内容不能为空');
      setTimeout(() => {
        axios.get('http://localhost:3004/news').then((res) => {
          setdataSource(res.data);
        });
      }, 0);
    } else {
      // console.log(value)
      setdataSource(result);
    }
  };
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '内容',
      dataIndex: 'content',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      render: (create_time) => {
        return moment(create_time * 1).format();
      },
    },
    {
      title: '图片',
      dataIndex: 'imgUrl',
      render: (imgUrl) => {
        return <img src={imgUrl} />;
      },
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div
            style={{
              display: 'flex',
            }}
          >
            <Button
              style={{
                marginRight: '12px',
              }}
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => confirmMethod(item)}
            />
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => handleUpdate(item)}
            />
          </div>
        );
      },
    },
  ];

  return (
    <div className={box}>
      <Search
        placeholder="请输入搜索内容"
        onSearch={onSearch}
        style={{ width: 400, marginRight: '100px' }}
        allowClear={true}
      />
      <Button
        type="primary"
        onClick={() => {
          addNews();
        }}
      >
        添加新闻
      </Button>
      <Table
        style={{
          margin: '18px auto',
          width: '96%',
        }}
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
        pagination={{
          pageSize: 5,
        }}
        bordered={true}
      />
      <Modal
        visible={isAddVisible}
        title="添加新闻"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false);
        }}
        onOk={() => {
          // console.log("add",addForm)
          addFormOK();
        }}
      >
        <NewsForm ref={addForm}></NewsForm>
      </Modal>

      <Modal
        visible={isUpdateVisible}
        title="更新新闻"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false);
        }}
        onOk={() => {
          // console.log("add",addForm)
          updateFormOK();
        }}
      >
        <NewsForm ref={updateForm}></NewsForm>
      </Modal>
    </div>
  );
}
